package com.channel.temperature.collect.ui.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import com.hjq.toast.ToastUtils
import com.hjy.bluetooth.HBluetooth.BleConfig
import com.hjy.bluetooth.exception.BluetoothException
import com.hjy.bluetooth.inter.BleMtuChangedCallback
import com.channel.temperature.collect.app.base.BaseActivity
import com.channel.temperature.collect.data.response.testresponse.Gun
import com.channel.temperature.collect.data.response.testresponse.Player
import com.channel.temperature.collect.databinding.Activity2TestBinding
import com.channel.temperature.collect.ui.viewmodel.MainViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import me.hgj.mvvmhelper.base.BaseViewModel
import me.hgj.mvvmhelper.ext.clickNoRepeat
import me.hgj.mvvmhelper.util.XLog
import kotlin.system.measureTimeMillis

class Test2Activity : BaseActivity<BaseViewModel, Activity2TestBinding>() {
    var count: Int = 1
    private val mainViewModel: MainViewModel by viewModels()
    private val mainscope = MainScope();
    private lateinit var registerForActivityResult: ActivityResultLauncher<Intent>
    override fun initView(savedInstanceState: Bundle?) {

//        countDownCoroutines(
//            10,
//            onTick = {
//                println("" + it)
//            },
//            onFinish = {
//                println("结束咯")
//            }
//        )
//        val flag = false
//        XLog.e("Answer is : ${if (flag) "hahahaha" else "heheheheehhe"} 你干嘛 $flag")
//        test("梁亚龙", 12)
//        test(age = 15, name = "张欣月")
//        println(test(age = 17, name = "张欣月111"))
//
//        val total: Int = "Mississippi".count({ testString ->
//            testString == 's'
//        })
//        println("total : " + total)
//        //变量的类型是一个匿名函数
//        val blessingFunction = { name: String, year: Int ->
//            val holiday = "New Year."
//            "$name 的年龄是 $year 岁,  sasas $holiday"
//        }
//        val result: String? = blessingFunction("张欣月", 17)
//        println("blessingFunction : " + result)

//        val showDiscount = { goodsName: String, hour: Int ->
//            val currentYear = 2027
//            "${currentYear} 年，双11${goodsName}促销倒计时:$hour 小时"
//        }
//        //展示
//        showOnBoard("笔记本") { goodsName: String, hour: Int ->
//            val currentYear = 2027
//            "${currentYear}年，双11${goodsName}促销倒计时:$hour 小时"
//        }
//        展示
//        showOnBoard("笔记本111", ::getDiscountWords)
//        val getConfigResult: (String) -> String = configDiscountWords()
//        XLog.e(getConfigResult("你大爷"))
//
//        val dataResult = HomeFragment.name.split(",")
//        for (index in dataResult.indices) {
//            XLog.e(dataResult.get(index))
//        }
//        XLog.e(formatGreeting(null))
//
//        val list = mutableListOf<String>("jason", "json", "jack")
//        list.add("Jimmy")
//        XLog.e("得到的值", "得到的值 ： " + list.toString())

//        val map = mutableMapOf("Jack" to 20, "Jason" to 18, "Jacky" to 30)
//        XLog.e("哈哈哈哈哈" + map.get("Jack"))
//        map.forEach {
//            XLog.e("这是它的key值 :" + it.value + " 这是它的key ：" + it.key)
//        }
//        map += "Liang" to 30
//        map.getOrPut("mali") { 18 }
//        XLog.e("map集合的大小  ：" + map.size)
//        map.forEach {
//            XLog.e("修改之后 这是它的key值 :" + it.value + " 这是它的key ：" + it.key)
//        }
//        test()
//        val p = Player2("laingyalong")
//        XLog.e(p.config)
//
//        val testP: Product = LuxuryProduct()
//        XLog.e(testP.load())
//
//        XLog.e(testP is Product)
//        XLog.e(testP is LuxuryProduct)
//        XLog.e(testP is Any)
//        if (testP is LuxuryProduct) {
//            XLog.e((testP as LuxuryProduct).specail())
//        }
//
//        XLog.e(SingletonTest.doSomething())
//
//        val copyPlayer = Player("张欣月", 24, false)
//        val copyPlayerTest = copyPlayer.copy("梁亚龙",26,true)
//        XLog.e("copy之后的值是 ： " + copyPlayerTest)
//        AK47(100)

//        val numbers = listOf(7, 4, 8, 4, 3, 22, 18, 11)
//        numbers.forEachIndexed { index, i ->
//            XLog.e("这里" + index + "   " + i)
//        }
//        val numbersflatMap = listOf(listOf(7, 4, 13), listOf(5, 6, 21))
//        val numbersResult = numbers.map { it + 2 }
//        val numbersResult1 = numbersflatMap.flatMap { it }
//        XLog.e(numbersResult)
//        XLog.e(numbersResult1)


//        val numbersResult2 = numbers.filter { it % 2 == 0 }
//        XLog.e(numbersResult2)
//
//        val numbersResult3 = numbersflatMap.flatMap { it.filter { it % 2 == 0 } }
//        XLog.e(numbersResult3)
//
//
//        val numbersResult4 = numbers.filter {
//            val temp = it + 1
//            temp % 2 == 0
//        }
//        XLog.e(numbersResult4)
//
//        val numbersResult5 = numbers.filter { number ->
//            (2 until number).map { number / it }.none { it > 2 }
//        }
//        XLog.e(numbersResult5)
//
//        val numbersZIP1 = listOf(7, 4, 8)
//        val numbersZIP2 = listOf(1, 2, 3, 4, 5, "sasa", 7)
//        val numbersZIPResult = numbersZIP1.zip(numbersZIP2).toMap()
//        XLog.e(numbersZIPResult)
//        val foldValue: Int = numbersZIP1.fold(0) { accumulator, number ->
//            XLog.e(accumulator)
//            accumulator + (number * 3)
//        }
//        XLog.e("最后的值"+foldValue)
//
//        val toList = (1..100).toList().filter { it % 2 == 0 }.take(10)
//        XLog.e(toList)
//        val toListResult = generateSequence(2) { value ->
//            value + 1
//        }.filter { it % 2 == 0 }.take(30)
//        XLog.e(toListResult.toList())
//        val myJavaTest = MyJavaTest()
//        XLog.e(myJavaTest.update())

//        GlobalScope.launch(Dispatchers.Main) {
//            val result = withContext(Dispatchers.IO) {
//                delay(4000)
//                "哈哈哈哈，这里是耗时操作"
//            }
//            ToastUtils.show(result)
//        }

//        GlobalScope.launch(Dispatchers.Main) {
//            //挂起
//            delay(4000)
//            ToastUtils.show("延迟提示数据了")
//        }

//        mainscope.launch {
//            val user = getUser()
//            ToastUtils.show(user)
//        }

        mBind.viewMdel = mainViewModel
        mBind.getUser.clickNoRepeat {
            ToastUtils.show("哈哈哈哈")
            count++
            mainViewModel.getuser(count)
        }

//        runBlocking {
//            flow {
//                emit(1)
//                emit(2)
//                emit(3)
//                emit(4)
//                emit(5)
//                emit(6)
//            }.filter {
//                it % 3 == 0
//            }.map { it * 2 }.take(4).collect {
//                XLog.e(it)
//            }
//        }


//        runBlocking {
//
//            val job1 = launch {
//                delay(2000)
//                XLog.e("launch协程")
//
//            }
//            val job2 = async(Dispatchers.Default) {
//                delay(2000)
//                XLog.e("async协程")
//                "job2 result"
//            }
//            XLog.e(job2.await())
//        }

//        runBlocking {
//
//            val job1 = launch {
//                delay(1000)
//                XLog.e("launch协程1111")
//
//            }
//            job1.join()
//            val job2 = launch {
//                delay(1000)
//                XLog.e("launch协程22222")
//
//            }
//            job2.join()
//            val job3 = launch {
//                delay(1000)
//                XLog.e("launch协程33333")
//
//            }
//        }


//        runBlocking {
//
//            val job1 = async {
//                delay(1000)
//                XLog.e("async协程1111")
//
//            }
//            job1.await()
//            val job2 = async {
//                delay(1000)
//                XLog.e("async协程22222")
//
//            }
//            job2.await()
//            val job3 = async {
//                delay(1000)
//                XLog.e("async协程33333")
//
//            }
//        }

//        runBlocking {
//            val time = measureTimeMillis {
//                val one = async { doOne() }
//                val two = async { doTwo() }
//                XLog.e("得到的值是 ：${one.await() + two.await()}")
//            }
//            XLog.e("完成咯 $time 毫秒")
//        }

//        runBlocking {
//            coroutineScope {
//                val time = measureTimeMillis {
//                    val one = async { doOne() }
//                    val two = async { doTwo() }
//                    XLog.e("得到的值是 ：${one.await() + two.await()}")
//                }
//                XLog.e("完成咯 $time 毫秒")
//            }
//        }

//        runBlocking {
//            val scope = CoroutineScope(Dispatchers.Default)
//            val job1 = scope.launch {
//                delay(1000)
//                XLog.e("job 1")
//            }
//           val job2 =  scope.launch {
//                delay(1000)
//                XLog.e("job 2")
//            }
//            delay(200)
//            job1.cancel()
//        }

//        runBlocking<Unit> {
//            launch {
//                for (k in 1..3) {
//                    XLog.e("测试是否阻塞$k")
//                    delay(2000)
//                }
//            }
//            simpleFlow().collect { value ->
//                XLog.e("flow操作后得到的值为$value")
//            }
//        }

//        runBlocking {
//            events().onEach {
//                XLog.e("Event: $it ${Thread.currentThread().name}")
//            }.launchIn(CoroutineScope(Dispatchers.IO)).join()
//        }

//        runBlocking {
//            withTimeoutOrNull(2500) {
//                simpleFlow2().collect {
//                    XLog.e("值 ：$it")
//                }
//            }
//        }

        runBlocking {
            val time = measureTimeMillis {
                simpleFlow3()
                    .buffer(50)
                    .collect {
                        delay(300)
                        XLog.e("Emitting $it ${Thread.currentThread().name}")
                    }
            }
            XLog.e("总共消耗时间 $time ms")
        }

//        runBlocking {
//            (1..3).asFlow().transform { request ->
//                emit("Making request $request")
//                emit(performRequest(request))
//                emit(doOtherThing(request))
//            }
//                .collect { value -> XLog.e(value) }
//        }

//        runBlocking {
//            numbers().take(2).collect {
//                XLog.e("执行得到的值 $it")
//            }
//            var list = (1..5).asFlow().map { it * it }.toList()
//            XLog.e("执行得到的列表值${list}")
//        }

//        runBlocking {
//            val nums = (1..3).asFlow().onEach { delay(1000) }
//            val strs = flowOf("one", "two", "three").onEach { delay(1500) }
//            nums.zip(strs) { a, b ->
//                "$a 加上了 $b"
//            }.collect() {
//                XLog.e(it)
//            }
//
//        }

//        弹窗
        //            MessageDialog.show(
//                "提示",
//                "跳转到设置界面打开蓝牙？",
//                "OK",
//                "Cancel"
//            ).okButtonClickListener =
//                OnDialogButtonClickListener { dialog, v ->
//                    ToastUtils.show("点击了ok")
//                    dialog.dismiss()
//                    registerForActivityResult.launch(Intent(Settings.ACTION_BLUETOOTH_SETTINGS))
//                    true
//                }

        registerForActivityResult =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                XLog.e("这里回调了")
            }

        val bleConfig = BleConfig()
        bleConfig.withServiceUUID("0000fe61-0000-1000-8000-00805f9b34fb")
            .withWriteCharacteristicUUID("0000fe61-0000-1000-8000-00805f9b34fb")
            .withNotifyCharacteristicUUID("0000fe61-0000-1000-8000-00805f9b34fb") //.liveUpdateScannedDeviceName(true)
            //命令长度大于20个字节时是否分包发送，默认false,分包时可以调两参方法设置包之间发送间隔
            //默认false,注释部分为默认值
            //.splitPacketToSendWhenCmdLenBeyond(false)
            //.useCharacteristicDescriptor(false)
            //连接后开启通知的延迟时间，单位ms，默认200ms
            //.notifyDelay(200)
            .setMtu(200, object : BleMtuChangedCallback {
                override fun onSetMTUFailure(realMtuSize: Int, bleException: BluetoothException) {
                    Log.i(
                        "HBluetooth",
                        "bleException:" + bleException.message + "  realMtuSize:" + realMtuSize
                    )
                }

                override fun onMtuChanged(mtuSize: Int) {
                    Log.i("HBluetooth", "Mtu set success,mtuSize:$mtuSize")
                }
            })
    }

    fun testBlocking() {
        CoroutineScope(Dispatchers.Default).launch {
            delay(8000)
            XLog.e("执行了想福安草做")
        }
    }

    fun numbers() = flow<Int> {
        try {
            emit(1)
            emit(2)
            XLog.e("我不执行咯")
            emit(3)
        } finally {
            XLog.e("这里是finally")
        }
    }

    suspend fun performRequest(request: Int): String {
        delay(1000)
        return "response $request"
    }

    suspend fun doOtherThing(request: Int): String {
        delay(1000)
        return "我在做其它事情 $request"
    }

    fun simpleFlow3() = flow<Int> {
        for (i in 1..3) {
            delay(100)
            emit(i)
            XLog.e("Emitting $i ${Thread.currentThread().name}")
        }
    }

    fun simpleFlow2() = flow<Int> {
        for (i in 1..3) {
            delay(1000)
            emit(i)
            XLog.e("Emitting $i")
        }
    }

    //事件源
    fun events() = (1..3).asFlow().onEach { delay(1000) }.flowOn(Dispatchers.Default)

    fun simpleFlow() = flow<Int> {
        for (i in 1..3) {
            delay(1000)
            emit(i)
        }
    }

    private suspend fun doOne(): Int {
        delay(3000)
        return 14
    }

    private suspend fun doTwo(): Int {
        delay(3000)
        return 10
    }

    private fun getUser(): String {
        return "这里是耗时操作"
    }

    override fun onBackPressed() {

        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        mainscope.cancel()
    }

    class AK47(val price: Int) : Gun(range = 500) {

        override fun pullTrigger(): String {
            XLog.e("先开始调用这个 $price")
            doSomething()
            return "哈哈哈"
        }


    }

    fun test() {
        var mPlayer = Player("hgah", 20, true)
        XLog.e(mPlayer.toString())

        var mPlayer2 = Player("测试次构造函数")
        XLog.e(mPlayer2.toString())

        var mPlayer3 = Player("zhangxinyue", 24)
        XLog.e(mPlayer3.toString())


    }

    fun formatGreeting(name: String?): String {
        return name?.let { "欢迎你哦，$it!" } ?: "你踏马谁啊？"
    }

    private fun configDiscountWords(): (String) -> String {
        val currentYear = 2027
        val hour: Int = 3
        return { goodsname: String ->
            "${currentYear}年，${hour}小时"
        }
    }


    private fun getDiscountWords(goodsName: String, hour: Int): String {
        val currentYear = 2027
        return "${currentYear}年，双11${goodsName}促销倒计时:$hour 小时"
    }

    private fun showOnBoard(goodsName: String, showDiscount: (String, Int) -> String) {
        val hour: Int = (1..24).shuffled().last();
        val result = getDiscountWords(goodsName, hour)
        XLog.e("啊哈 $result")
    }


    fun test(name: String, age: Int) {
        println(name + "    " + age)
    }
}